package com.youhong.teethcare.settingpage;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.youhong.cuptime.blesdk.BleService;
import com.youhong.teethcare.BaseActivity;
import com.youhong.teethcare.ConnectIntroduceActivity;
import com.youhong.teethcare.DeviceListActivity;
import com.youhong.teethcare.MainActivity;
import com.youhong.teethcare.R;
import com.youhong.teethcare.dialogs.DeviceNotFoundDialog;
import com.youhong.teethcare.dialogs.DeviceNotScannedDialog;
import com.youhong.teethcare.receiver.TimerService;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.utils.AppManager;
import com.youhong.teethcare.utils.BTUtils;
import com.youhong.teethcare.utils.BraceletDevice;
import com.youhong.teethcare.utils.DBHelper;
import com.youhong.teethcare.utils.DialogUtil;
import com.youhong.teethcare.utils.GpsUtil;
import com.youhong.teethcare.utils.PermissionsUtils;
import com.youhong.teethcare.utils.ToastUtil;
import com.youhong.teethcare.utils.Tools;

import java.util.Set;

public class DeviceManagerActivity extends BaseActivity implements View.OnClickListener {

    BluetoothAdapter mBluetoothAdapter = null;
    RelativeLayout rl_deviceInfo, rl_pair;
    LinearLayout ll_userInfo;


    ImageView iv_back, iv_rssi, iv_pair, iv_prepair;
    TextView tv_name, tv_mac, tv_connect, tv1, tv2;
    Button btn_unpair, btn_next, btn_pair;

    TextView tv_username, tv_battery, tv_firmwareVersion, tv_appVersion;

    private int REQUEST_ENABLE_BT = 0x5AA;
    private int REQUEST_DEVICE_LIST = 0x5AB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_manager);
        AppManager.getInstance().addActivity(this);
        initStatusBar(getResources().getColor(R.color.pageBackground), true);

        tv_username = findViewById(R.id.deviceManager_tv_username);
        tv_battery = findViewById(R.id.deviceManager_tv_battery);
        tv_firmwareVersion = findViewById(R.id.deviceManager_tv_firmwareVersion);
        tv_appVersion = findViewById(R.id.deviceManager_tv_appVersion);

        tv1 = findViewById(R.id.deviceManager_tv1);

        tv2 = findViewById(R.id.deviceManager_tv2);

        ll_userInfo = findViewById(R.id.deviceManager_ll_userInfo);

        btn_pair = findViewById(R.id.deviceManager_btn_pair);
        btn_pair.setOnClickListener(this);

        rl_pair = findViewById(R.id.deviceManager_rl_pair);

        iv_prepair = findViewById(R.id.deviceManager_iv_prepair);

        iv_pair = findViewById(R.id.deviceManager_iv_pair);

        btn_next = findViewById(R.id.deviceManager_btn_next);
        btn_next.setOnClickListener(this);

        iv_back = findViewById(R.id.deviceManager_iv_back);
        iv_back.setOnClickListener(this);

        if (AppManager.getInstance().getSpecificActivity(MainActivity.class) == null) {

            iv_back.setVisibility(View.GONE);
        }

        rl_deviceInfo = findViewById(R.id.deviceManager_rl_deviceInfo);

        tv_name = findViewById(R.id.chosenDevice_tv_deviceName);
        tv_mac = findViewById(R.id.chosenDevice_tv_deviceMac);

        tv_connect = findViewById(R.id.chosenDevice_tv_rssi);
        iv_rssi = findViewById(R.id.chosenDevice_iv_rssiIcon);
        btn_unpair = findViewById(R.id.chosenDevice_btn_disconnect);
        btn_unpair.setOnClickListener(this);

        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        registerReceiver(receiver, filter);


//        if (MainActivity.mDevice == null) {
//
//            ll_userInfo.setVisibility(View.GONE);
//
//        } else {

            tv_firmwareVersion.setText(Common.userInfo.getDeviceVersion());
            tv_appVersion.setText(Common.appVersion);
            tv_battery.setText(Common.battery + "%");
            tv_username.setText(Common.userInfo.getNickName());

      //  }

        if (Common.userInfo.getMac() != null && !Common.userInfo.getMac().equals("")) {

            //隐藏连接时的提示信息。
            displayConnectionInfo(false);
            //显示绑定设备的信息。
            displayDeviceInfo(true);


            //只有在已经进入主页后，进入这个页面才会显示
            //因为在第一次绑定的时候，UserName 都没填

            if (AppManager.getInstance().getSpecificActivity(MainActivity.class) != null
                    && MainActivity.mDevice != null
            ) {

                ll_userInfo.setVisibility(View.VISIBLE);

            }
        }
    }

    private void displayDeviceInfo(boolean display) {
        if (display) {

            if (AppManager.getInstance().getSpecificActivity(MainActivity.class) != null) {

                btn_next.setVisibility(View.GONE);

            } else {

                btn_next.setVisibility(View.VISIBLE);

            }

            tv_mac.setText(Common.userInfo.getMac());
            tv_name.setText(Common.userInfo.getDeviceName());

            //主动断开连接时，应将MainActivity.mDevice 赋值为Null
            if (MainActivity.mDevice != null) {

//                tv_connect.setText(R.string.chosenDevice_str2);
//
//                iv_rssi.setImageDrawable(getResources().getDrawable(R.mipmap.icon_rssi3));
                showDeviceState(MainActivity.mDevice.isConnected());

            } else {
//                tv_connect.setText(R.string.chosenDevice_str3);
//                iv_rssi.setImageDrawable(getResources().getDrawable(R.mipmap.icon_rssi0));
                    showDeviceState(false);
            }
            rl_deviceInfo.setVisibility(View.VISIBLE);

        } else {

            rl_deviceInfo.setVisibility(View.GONE);
            btn_next.setVisibility(View.GONE);

        }


    }
    void showDeviceState(boolean isConnect){
      //  iv_rssi.setImageDrawable(getResources().getDrawable(isConnect ? R.mipmap.icon_rssi3:R.mipmap.icon_rssi1));
        Drawable drawableTarget = DrawableCompat.wrap(iv_rssi.getDrawable().mutate());
        DrawableCompat.setTintList(drawableTarget, ColorStateList.valueOf(isConnect?getResources().getColor(R.color.mainColor): Color.GRAY));
        iv_rssi.setImageDrawable(drawableTarget);
        tv_connect.setText(getString(isConnect ? R.string.chosenDevice_str2 : R.string.chosenDevice_str3));
    }
    private void displayConnectionInfo(boolean display) {

        if (display) {
            //显示连接时的提示信息。
            btn_pair.setVisibility(View.VISIBLE);
            //iv_pair.setVisibility(View.VISIBLE);
            iv_prepair.setVisibility(View.VISIBLE);
            rl_pair.setVisibility(View.VISIBLE);

        } else {
            //隐藏连接时的提示信息。
            tv1.setVisibility(View.GONE);
            tv2.setVisibility(View.GONE);
            btn_pair.setVisibility(View.GONE);
            iv_pair.setVisibility(View.GONE);
            iv_prepair.setVisibility(View.GONE);
            rl_pair.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        mHandler.removeCallbacksAndMessages(null);

    }

    private void enableBluetooth() {
        Intent enableBtIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);


    }

    private void showChangeBondDialog() {
        new AlertDialog.Builder(this)
                .setMessage(
                        getResources()
                                .getString(
                                        R.string.Whether_to_replace_the_binding_of_bracelets))
                .setTitle(
                        getResources().getString(
                                R.string.Switch_binding_bracelet))
                .setIconAttribute(android.R.attr.alertDialogIcon)
                .setCancelable(true)
                .setPositiveButton(R.string.LogOut_tv_comfirm,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                if (MainActivity.mDevice != null) {
                                    MainActivity.mDevice.getBrushingData((byte) 0xFE);

                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {

                                            MainActivity.mDevice.disconnectedDevice();
                                            MainActivity.mDevice = null;

                                        }
                                    }, 200);

                                }

                                Common.isNeedToUpdate = false;
                                Common.userInfo.setMac("");
                                Common.userInfo.setLastSyncTime(0);
                                Common.userInfo.setScore(0);
                                Common.userInfo.SyncToLocal(getApplicationContext());

                                displayDeviceInfo(false);
                                displayConnectionInfo(true);
                                ll_userInfo.setVisibility(View.GONE);

                                DBHelper.getDbHelper(getApplicationContext()).deleteBrushRecords();

                            }
                        })
                .setNegativeButton(R.string.LogOut_tv_cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                if (MainActivity.mDevice != null) {
                                    MainActivity.mDevice.disconnectedDevice();
                                    MainActivity.mDevice = null;
                                }

                                Common.isNeedToUpdate = false;
                                Common.userInfo.setMac("");
                                Common.userInfo.setLastSyncTime(0);
                                Common.userInfo.setScore(0);
                                Common.userInfo.SyncToLocal(getApplicationContext());

                                displayDeviceInfo(false);
                                displayConnectionInfo(true);
                                ll_userInfo.setVisibility(View.GONE);
                                DBHelper.getDbHelper(getApplicationContext()).deleteBrushRecords();

                            }
                        }).create().show();
        // TODO Auto-generated method stub
    }

    boolean manuallyDisconnect = false;

    BluetoothDevice connected_device = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {

            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        1);
            } else {
                getPairedInfo();
                if (pairedDevice == null) {
                    displayScanning(true);
                }
            }
        } else if (requestCode == REQUEST_DEVICE_LIST && resultCode == Activity.RESULT_OK) {

            connected_device = data.getParcelableExtra("device");

            MainActivity.mDevice = new BraceletDevice(getApplicationContext(), connected_device.getAddress());
            MainActivity.mDevice.connected(connected_device.getAddress());
            startConntDialog();

        } else if (requestCode == REQUEST_DEVICE_LIST && resultCode == Activity.RESULT_CANCELED) {

            displayScanning(false);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //如果当前没有配对的牙刷设备，则还是弹出设备列表进行扫描
            if (pairedDevice == null) {
                displayScanning(true);
            }
        }
        //super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction() == BleService.ACTION_GATT_SERVICES_DISCOVERED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                 /*连接成功后，有俩套逻辑：
                            1.首次打开APP进行连接：不显示UserInfo,连接成功后，
                              立刻把ConnectingDialog消失掉。并且显示Next 按钮

                            2.通过设置界面进行连接：显示UserInfo，连接成功后，
                              不立刻把ConnectingDialog消失掉，开始获取电量，和固件版本号
                              ，不显示Next按钮
                 */
                        Common.userInfo.setMac(connected_device.getAddress());
                        Common.userInfo.setDeviceName(connected_device.getName());
                        Common.userInfo.SyncToLocal(getApplicationContext());

                        displayDeviceInfo(true);
                        //只有在已经进入主页后，进入这个页面才会显示
                        //因为在第一次绑定的时候，UserName 都没填
                        //首次打开APP进行连接连接
                        if (AppManager.getInstance().getSpecificActivity(MainActivity.class) != null) {
                            ll_userInfo.setVisibility(View.VISIBLE);
                            displayConnectionInfo(false);
                            connectDialog.cancel();
                            ToastUtil.showShortToast(context, R.string.strings113_2);

                            //非首次进行连接
                        } else {

                            displayConnectionInfo(false);
                            // connectDialog.cancel();
                            ToastUtil.showShortToast(context, R.string.strings113_2);
                        }
                    }
                });

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        MainActivity.mDevice.getVersion();
                    }
                }, 500);
                mHandler.removeCallbacks(runnable_connectDialogWatchDog);
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        mHandler.removeCallbacks(runnable_connectDialogWatchDog);
//                        //启动Service 去同步battery,历史数据
//                        Intent intent = new Intent(getApplicationContext(), TimerService.class);
//                        intent.putExtra(TimerService.EXTRA_COMMAND_ID, TimerService.COMMAND_SYNC);
//                        startService(intent);
//                    }
//
//                }, 300);

            } else if (intent.getAction() == BleService.ACTION_GATT_DISCONNECTED) {

                if (connectDialog != null) {
                    connectDialog.cancel();
                }
                if (manuallyDisconnect == false) {
                    //清空WatchDog
                    mHandler.removeCallbacks(runnable_connectDialogWatchDog);
                    //显示，连接失败的Dialog
                    //runnable_connectDialogWatchDog.run();
                    // ToastUtil.showShortToast(context, R.string.strings20);

                } else {
                    manuallyDisconnect = false;
                    ToastUtil.showShortToast(context, R.string.strings113);

                }
                showDeviceState(false);
            } else if (intent.getAction() == BleService.ACTION_DATA_AVAILABLE) {

                byte[] values = intent.getByteArrayExtra(BleService.EXTRA_DATA);

                if (values[0] == (byte) 0x13) {

                   /* Common.battery = values[1] & 0xFF;
                    MainActivity.mDevice.getVersion();*/

                } else if (values[0] == (byte) 0x27) {
                    String version = ((values[1] - 0x30) + "." + (values[2] - 0x30) + "."
                            + (values[3] - 0x30) + "." + (values[4] - 0x30));
                    tv_firmwareVersion.setText(version);
                    tv_appVersion.setText(Common.appVersion);
                    tv_battery.setText(Common.battery + "%");
                    tv_username.setText(Common.userInfo.getNickName());
                    if (connectDialog != null) {
                        connectDialog.cancel();
                    }
                }
            }
        }
    };

    Dialog not_found_dialog;

    Runnable runnable_connectDialogWatchDog = new Runnable() {
        @Override
        public void run() {

            //connectDialog.hide();
            if (connectDialog != null) {
                connectDialog.dismiss();
                connectDialog = null;
            }
            if (not_found_dialog == null) {
                not_found_dialog = new DeviceNotFoundDialog(DeviceManagerActivity.this, runnable_iv_close);

            }
            try {
                not_found_dialog.show();
            } catch (Exception exp) {

            }

            //Toast.makeText(getApplicationContext(), R.string.strings20, Toast.LENGTH_SHORT).show();
            if(MainActivity.mDevice!=null)MainActivity.mDevice.disconnectedDevice();
            MainActivity.mDevice = null;

        }
    };

    Runnable runnable_iv_close = new Runnable() {
        @Override
        public void run() {
            not_found_dialog.dismiss();
            displayScanning(false);
            displayConnectionInfo(true);

        }
    };

    ProgressDialog connectDialog;

    private void startConntDialog() {
        connectDialog = new ProgressDialog(this);
        connectDialog.setMessage(getResources()
                .getString(R.string.strings19));
        connectDialog.setCancelable(false);
        connectDialog.show();


        mHandler.postDelayed(runnable_connectDialogWatchDog, 20000);
        // timer = new Timer();
        // task = new TimerTask() {
        // @Override
        // public void run() {
        // // TODO Auto-generated method stub
        // if (connectDialog.isShowing()) {
        // connectDialog.dismiss();
        // }
        // }
        // };
        // timer.schedule(task, 20000);
    }

    private void displayScanning(boolean display) {

        if (display) {
            btn_pair.setVisibility(View.GONE);
            tv1.setVisibility(View.VISIBLE);
            tv2.setVisibility(View.VISIBLE);
            iv_prepair.setVisibility(View.GONE);
            iv_pair.setVisibility(View.VISIBLE);

            AnimationDrawable drawable = (AnimationDrawable) iv_pair.getDrawable();
            drawable.start();
            startScan(true);

        } else {

            btn_pair.setVisibility(View.VISIBLE);
            tv1.setVisibility(View.GONE);
            tv2.setVisibility(View.GONE);
            iv_prepair.setVisibility(View.VISIBLE);
            iv_pair.setVisibility(View.GONE);

            AnimationDrawable drawable = (AnimationDrawable) iv_pair.getDrawable();
            drawable.stop();
        }
    }

    BluetoothDevice pairedDevice = null;

    private void getPairedInfo() {

        BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);

        //获取配对设备的列表

        //  manager.getConnectionState()

        Set<BluetoothDevice> pairedDevices = manager.getAdapter().getDefaultAdapter().getBondedDevices();
        if (pairedDevices.size() > 0) {

            for (BluetoothDevice d : pairedDevices) {
                String deviceName = d.getName();

                if (deviceName.contains("1741")
                        || deviceName.contains("1835")

                ) {

                    boolean isConnected = BTUtils.isBluetoothConnected(d, getApplicationContext());
                    //只有当设备被绑定而且此时已经被系统蓝牙连接上的时候，才会提示
                    if (isConnected) {
                        pairedDevice = d;
                    }
                }
            }
        }

        if (pairedDevice != null) {
            DialogUtil.showModalDialog(DeviceManagerActivity.this, R.string.strings115,
                    R.string.strings84,
                    R.string.strings98,
                    R.string.strings99,
                    new Runnable() {
                        @Override
                        public void run() {
                            Common.userInfo.setMac(pairedDevice.getAddress());
                            Common.userInfo.setDeviceName(pairedDevice.getName());

                            MainActivity.mDevice = new BraceletDevice(getApplicationContext(), Common.userInfo.getMac());
                            MainActivity.mDevice.connected(Common.userInfo.getMac());
                            startConntDialog();

                        }
                    }, new Runnable() {
                        @Override
                        public void run() {

                            displayScanning(true);

                        }
                    }
            );
        }
    }

    DeviceNotScannedDialog dialog = null;

    //Skip ，跳入下一个页面
    Runnable runnable_skip = new Runnable() {
        @Override
        public void run() {
            dialog.dismiss();
            Intent intent = new Intent(getApplicationContext(), ConnectIntroduceActivity.class);
            startActivity(intent);
        }
    };

    Runnable runnable_refresh = new Runnable() {
        @Override
        public void run() {
            startScan(true);
            dialog.hide();
        }
    };

    Runnable runnable_close = new Runnable() {
        @Override
        public void run() {

            displayScanning(false);
            displayConnectionInfo(true);
            dialog.hide();

        }
    };

    @Override
    public void onClick(View v) {

        if (v == btn_pair) {

            if (!mBluetoothAdapter.isEnabled()) {
                enableBluetooth();
                return;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                    && !GpsUtil.isOPen(DeviceManagerActivity.this)
            ) {
                Toast.makeText(this, "Please turn on the GPS " +
                        "before search a device.", Toast.LENGTH_LONG).show();
                GpsUtil.openGPS(DeviceManagerActivity.this);
                return;

            }

            getPairedInfo();
            //动态申请权限，因为6.0之后蓝牙被加入用户Location权限组了。 被认为是
            //Critical Permission.

            PermissionsUtils.getPermission_Location(this, new PermissionsUtils.PermissionsUtilsListener() {
                @Override
                public void onSuccess() {
                    //如果当前没有配对的牙刷设备，则还是弹出设备列表进行扫描
                    if (pairedDevice == null) {
                        displayScanning(true);
                    }
                }

                @Override
                public void onfail() {

                    String abc="asdasdsad";
                }
            });

        } else if (v == iv_back) {

            //如果是在用户第一次登陆时点击了左上角的返回图标，则退出APP。
            if (AppManager.getInstance().getSpecificActivity(MainActivity.class) == null) {

                AppManager.getInstance().killAllActivity();
                // System.exit(0);
            } else {

                AppManager.getInstance().killTopActivity();
            }

        } else if (v == btn_unpair) {
            manuallyDisconnect = true;
            showChangeBondDialog();

        } else if (v == btn_next) {

            Intent intent = new Intent(getApplicationContext(), ConnectIntroduceActivity.class);
            startActivity(intent);
        }

    }

    Handler mHandler = new Handler();
    boolean isScanning = false;

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {

             String dev_name = Tools.decodeDeviceName(scanRecord);
            if(TextUtils.isEmpty(dev_name))dev_name="Unkonw Device";
            if (dev_name.toLowerCase().contains("fg")|| (dev_name.contains("1741")
                    || dev_name.toLowerCase().contains("1835") || dev_name.toLowerCase().contains("agu"))
                    || dev_name.toLowerCase().contains("j2058a")|| dev_name.toLowerCase().contains("j2002a")|| dev_name.toLowerCase().contains("j2002")

            ) {

                if (isScanning) {

                    isScanning = false;
                    startScan(false);
                    Intent intent = new Intent(getApplicationContext(), DeviceListActivity.class);
                    intent.putExtra("device", device);
                    intent.putExtra("rssi", rssi);

                    startActivityForResult(intent, REQUEST_DEVICE_LIST);
                }
            }
        }
    };

    Runnable runnable_scanningWatchDog = new Runnable() {
        @Override
        public void run() {
            try {
                startScan(false);
                dialog = new DeviceNotScannedDialog(
                        DeviceManagerActivity.this, runnable_refresh,
                        runnable_skip, runnable_close);
                dialog.show();
            } catch (Exception exp) {

            }
        }
    };

    private void startScan(boolean enable) {
        // TODO Auto-generated method stub
        if (enable) {
            mHandler.postDelayed(runnable_scanningWatchDog, 20000);
            //deviceAdapter.clear();
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            isScanning = true;

            /*if (bt_cancle != null) {
                bt_cancle.setText(getResources().getString(R.string.stop_scan));
            }*/
        } else {
          /*  deviceDialog.dismiss();
            bt_cancle.setText(getResources().getString(R.string.start_scan));
           */
            mHandler.removeCallbacksAndMessages(null);
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            isScanning = false;
        }

    }

    @Override
    public void onBackPressed() {

        //当用户作为首次进入APP，在这个界面按返回键时退出APP
        if (AppManager.getInstance().getSpecificActivity(MainActivity.class) == null) {

            AppManager.getInstance().killAllActivity();
        } else {
            super.onBackPressed();
        }
    }
}